package com.zys.http.ui.tab.panel;

import com.intellij.openapi.project.Project;
import com.intellij.ui.components.JBPanel;
import com.intellij.util.ui.JBUI;
import com.zys.http.constant.HttpEnum;
import com.zys.http.constant.UIConstant;
import com.zys.http.entity.ReqHistory;
import com.zys.http.entity.param.ParamProperty;
import com.zys.http.tool.HttpServiceTool;
import com.zys.http.ui.table.EnvHeaderTable;
import jdk.jfr.Description;
import lombok.Getter;

import java.awt.*;
import java.util.Map;

/**
 * @author zys
 * @since 2025-02-19
 */
@Getter
public class RequestHeaderPanel extends JBPanel<RequestHeaderPanel> implements TabOperation {
    @Description("请求头表格")
    private final EnvHeaderTable headerTable;

    public RequestHeaderPanel(Project project) {
        super(new BorderLayout(0, 0));
        this.headerTable = new EnvHeaderTable(project, false, HttpServiceTool.getInstance(project).getSelectedEnv());
        this.headerTable.getToolbar().getComponent().setBorder(JBUI.Borders.customLineBottom(UIConstant.BORDER_COLOR));
        this.add(headerTable);
    }

    @Override
    public void reset() {
        this.headerTable.reloadTableModel();
    }

    @Override
    public void execute(HttpEnum.HttpMethod httpMethod, HttpEnum.ContentType contentType, String param, Map<String, ParamProperty> paramPropertyMap) {
        ParamProperty v = paramPropertyMap.get(param);
        HttpEnum.ParamUsage usage = v.getParamUsage();
        switch (usage) {
            case HEADER -> this.headerTable.getTableModel().addRow(new String[]{param, v.getDefaultValue() + ""});
            case BODY -> {
                if (contentType.equals(HttpEnum.ContentType.APPLICATION_JSON)) {
                    this.headerTable.addContentType(HttpEnum.ContentType.APPLICATION_JSON.getValue());
                }
            }
            case FILE -> this.headerTable.addContentType(HttpEnum.ContentType.MULTIPART_FORM_DATA.getValue());
            default -> {

            }
        }
    }

    @Override
    public void recover(ReqHistory history) {
        this.headerTable.setModel(history.getHeaders());
    }
}
